package com.yuexun.dhdoctor.module.departmentDocumentNew;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.AlreadyShareObjListAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.DocMemberBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.MemberListBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.ShareDocBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.ShareMemberModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.SetShareMemberPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.ShareMemberListPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.ISetShareMemberView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IShareMemberListView;
import com.yuexun.dhdoctor.util.ListChangeUtil;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;


import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的共享文档-已添加对象
 * Created by wangt on 2017/7/20.
 */

public class Act_Document_Share_My_MemberList extends BaseKJActivity implements IShareMemberListView, ISetShareMemberView {
    @Bind(R.id.ib_right)
    TextView right;

    @Bind(R.id.lv_doc_member)
    PullToRefreshList pullToRefreshList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    @Bind(R.id.rl_doc_member_nor)
    RelativeLayout rlNor;
    @Bind(R.id.rl_doc_member_del)
    RelativeLayout rlDel;
    @Bind(R.id.cb_doc_member_all)
    CheckBox cbAll;

    private boolean isDelete = false;

    private ShareDocBean nowDoc;

    private ListView mList;
    private ShareMemberListPresenter presenter;
    private List<MemberListBean> memberList = new ArrayList<>();
    private AlreadyShareObjListAdapter adapter;

    private SetShareMemberPresenter setPresenter;

    private LoadingDialog loadingDialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_document_share_memberlist);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        nowDoc = (ShareDocBean) getIntent().getSerializableExtra("docinfo");
        presenter = new ShareMemberListPresenter(this, new ShareMemberModel());
        setPresenter = new SetShareMemberPresenter(this, new ShareMemberModel());
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCanceledOnTouchOutside(true);

//        if (getIntent().getStringExtra("member").equals("[]")) {
        ApiGetMemberList();
//        } else {
//            memberList = JSON.parseArray(getIntent().getStringExtra("member"), MemberListBean.class);
//        }
        initView();

    }

    private void initView() {
        pullToRefreshList.setPullRefreshEnabled(false);
        mList = pullToRefreshList.getRefreshView();
        adapter = new AlreadyShareObjListAdapter(mList, memberList, R.layout.item_doc_department_select);
        mList.setAdapter(adapter);

        cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean is) {
                setSelectAll(is);
            }
        });
    }

    @OnClick({R.id.back, R.id.ib_right, R.id.btn_doc_member_del, R.id.tv_doc_member_add, R.id.tv_doc_member_ok})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ib_right:
                showDel(!isDelete);
                break;
            case R.id.btn_doc_member_del:
                setDelete();
                break;
            case R.id.tv_doc_member_add:
                ArrayList<People> usersBeans_origin = new ArrayList<>();
                for (MemberListBean item : memberList) {
                    People people = new People();
                    people.setUserId(item.getMemberId() + "");
                    people.setUserName(item.getMemeberName());
                    usersBeans_origin.add(people);
                }

                Bundle bundle = new Bundle();
                Intent intent = new Intent(this, Act_Choice_Member.class);
                bundle.putSerializable("persons", usersBeans_origin);
                bundle.putString("title", "共享设置");
                bundle.putString("type", "多选");
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_doc_member_ok:
                setUpdate();
                break;
        }
    }

    @Override
    public void showMemberList(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            if (bean.getDatas().size() != 0) {
                DocMemberBean item = JSON.parseObject(bean.getDatas().get(0), DocMemberBean.class);
                memberList = JSON.parseArray(item.getMemberIds(), MemberListBean.class);
                adapter.refresh(memberList);
            }
        } else {
            ViewInject.toast("获取数据失败");
        }

        emptyLayout.dismiss();
    }

    //请求列表
    private void ApiGetMemberList() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("shareType", nowDoc.getShareType() + "");
        params.put("docId", nowDoc.getDocId() + "");
        presenter.getMemberDatas(params);
    }

    //设置显示删除
    private void showDel(boolean is) {
        if (is) {
            adapter.setDo(true);
            rlDel.setVisibility(View.VISIBLE);
            rlNor.setVisibility(View.GONE);
            right.setText("取消");
            isDelete = true;
        } else {
            adapter.setDo(false);
            rlDel.setVisibility(View.GONE);
            rlNor.setVisibility(View.VISIBLE);
            right.setText("删除");
            isDelete = false;
        }
        emptyLayout.dismiss();
    }

    //全选
    private void setSelectAll(boolean is) {
        for (MemberListBean item : memberList) {
            item.setSelect(is);
        }
        adapter.notifyDataSetChanged();
    }

    //设置删除
    private void setDelete() {
        List<MemberListBean> selMember = new ArrayList<>();
        for (MemberListBean item : memberList) {
            if (item.isSelect()) {
                selMember.add(item);
            }
        }
        if (selMember.size() == 0) {
            ViewInject.toast("请选择删除对象");
        } else {
            memberList.removeAll(selMember);
            adapter.notifyDataSetChanged();
            showDel(false);
        }
    }

    //确定提交
    private void setUpdate() {
        List<String> idList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        String strId;
        String strName;

        if (memberList.size() == 0) {
            ViewInject.toast("共享对象不能为空");
        } else {
            loadingDialog.show();
            for (MemberListBean item : memberList) {
                idList.add(item.getMemberId() + "");
                nameList.add(item.getMemeberName());
            }
            strId = ListChangeUtil.listToString(idList, ";");
            strName = ListChangeUtil.listToString(nameList, ";");

            Map<String, String> params = new HashMap<>();
            params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
            params.put("memberId", strId);
            params.put("memberName", strName);
            params.put("departDocId", "b_" + nowDoc.getDocId());
            params.put("fileType", nowDoc.getFileType() + "");
            setPresenter.setShareMember(params);
        }
    }


    @Override
    public void setShareMember(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            ViewInject.toast("提交成功");
            Intent intent = new Intent();
            intent.putExtra("result", "result");
            setResult(1, intent);
            finish();
        } else {
            ViewInject.toast("提交数据失败");
        }
        loadingDialog.dismiss();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                ArrayList<People> peoples = (ArrayList<People>) data.getExtras().getSerializable("persons");
                memberList.clear();
                if (peoples != null){
                    for (People people : peoples) {
                        MemberListBean item = new MemberListBean();
                        item.setMemberId(Integer.parseInt(people.getUserId()));
                        item.setMemeberName(people.getUserName());
                        memberList.add(item);
                    }
                }

                adapter.notifyDataSetChanged();
                break;
        }
    }
}
